<?php
class AlbumsController extends AppController {
	var $name = 'Albums';

    public function eventForm ($id='') {
        if (!$this->_checkLogged('A')) {
            return;
        }

        $dt = array(
            'id'          => '',
            'name'        => '',
            'description' => ''
        );

        if ($id) {
            $data = $this->Album->read(array('id', 'name', 'description'), $id);
            if (count($data) > 0) {
                $dt = $data['Album'];
            }
        }

        $this->set('data', $dt);
        $this->render('form', 'blank');
    } // eventForm

    public function update () {
        if (!$this->_checkLogged('A')) {
            return;
        }

        $this->data['Album'] = $this->params['form'];

        if ($this->data) {
            $valid = true;

            foreach ($this->data['Album'] as $fieldname=>$value) {
                if (empty($value) && $value != '0') {
                    $this->data['Album'][$fieldname] = null;
                }
            }

            $this->Album->set($this->data);

            if ($this->Album->validates() && $valid) { // data validated!
                if ($this->Album->save($this->data)) {
                    $mesg = empty($this->params['form']['id']) ? __('New event has been created successfully!',true) : __('Event has been updated successfully!',true);
                    $json = array(
                        'status' => true,
                        'id'     => $this->Album->id,
                        'mesg'   => $mesg
                    );
                } else {
                    $mesg = empty($this->params['form']['id']) ? __('Fail insert event to database at this time, please try again.',true) : __('Fail update event to database at this time, please try again.',true);
                    $err  = ($this->error) ? $this->error : $mesg;
                    $json = array(
                        'status' => false,
                        'mesg'   => $err
                    );
                }
            } else { // invalid data found
                $json = array(
                    'status' => false,
                    'mesg'   => __('Please enter the requested details in the fields pointed out below and try again!', true)
                );
                foreach ($this->Album->invalidFields() as $k=>$v) {
                    $json['error'][] = array('id'=>$k, 'field'=>$k, 'code'=>$v);
                }
            }
        } else {
            $json = array(
                'status' => false,
                'mesg'   => __('no data posted', true)
            );
        }

        $this->response($json);
    } // update

    public function manage () {
        if (!$this->_checkLogged('A')) {
            return;
        }

        $this->helpers = array_merge($this->helpers, array('Time'));

        $params = array(
            'conditions' => array('type' => 'events'),
            'recursive'  => -1,
            'order'      => array('order', 'id'),
            'limit'      => 10
        );
        $this->paginate = $params;

        $data = $this->paginate();
        $this->loadModel('Image');

        foreach ($data as $i=>$a) {
            $data[$i]['Album']['filename'] = '';

            if ($a['Album']['image_id']) {
                $this->Image->id = $a['Album']['image_id'];
                $data[$i]['Album']['filename'] = $this->Image->field('filename');
            }
        }

        $this->pageTitle = __('Manage Events',true);
        $this->set('data', $data);
    } // manage

    public function remove () {
        if (!$this->_checkLogged('A')) {
            return;
        }

        $form = $this->params['form'];

        if (isset($form['delete'])) {
            $this->loadModel('Image');
            $data = $this->Image->find('all', array(
                'conditions' => array('album_id' => $form['ids']),
                'recursive'  => -1,
                'fields'     => array('filename')
            ));
            if ($this->Album->deleteAll(array('id' => $form['ids']))) {
                $path = IMAGES.'events'.DS;

                foreach ($data as $g) {
                    $file = $g['Image']['filename'];
                    @unlink($path.'s_'.$file);
                    @unlink($path.'t_'.$file);
                    @unlink($path.$file);
                }
                $this->Session->setFlash('<h4>'.__('Selected event has been deleted.',true).'</h4>', 'default', array('class'=>'boxSuccess'));
            } else {
                $this->Session->setFlash('<h4>'.__('Fail deleting event at this time, please try again.',true).'</h4>', 'default', array('class'=>'boxError'));
            }
        } else if (isset($form['update'])) {
            foreach ($form as $k=>$v) {
                if (strpos($k, 'dr_')) {
                    $id = str_replace('odr_', '', $k);

                    $this->Album->id = $id;
                    $this->Album->saveField('order', $v);
                }
            }
            $this->Session->setFlash('<h4>'.__('Event has been updated.',true).'</h4>', 'default', array('class'=>'boxSuccess'));
        }

        $this->redirect('/albums/manage');
    } // remove

    public function view ($id) {
        $width  = 900;
        $height = 500;

        if ($this->RequestHandler->isXml()) {
            Configure::write('debug', 0);

            $data = $this->Album->find('first', array(
                'conditions' => array('Album.id' => $id),
                'fields'     => array('Album.type', 'Album.name')
            ));

            if (count($data) > 0) {
                $type = 'events';
                $xml  = '<simpleviewergallery' .
                        ' title="'.addslashes($data['Album']['name']).'" textColor="333333" frameColor="ffffff" thumbPosition="LEFT" galleryStyle="MODERN"' .
                        ' thumbColumns="3" thumbRows="2" showOpenButton="TRUE" showFullscreenButton="TRUE" frameWidth="10" maxImageWidth="'.$width.'" maxImageHeight="800"' .
                        ' imagePath="'.$type.'/" thumbPath="'.$type.'/" useFlickr="false" flickrUserName="" flickrTags="" languageCode="AUTO" languageList="">';
                $path = $this->base.'/img/'.$type.'/';

                foreach ($data['Image'] as $img) {
                    $ttle = empty($img['title']) ? '' : '<b>'.$img['title'].'</b>';
                    $desc = empty($img['description']) ? '' : '<div>'.$img['description'].'</div>';
                    $xml .= '<image imageURL="'.$path.$img['filename'].'" thumbURL="'.$path.'s_'.$img['filename'].'" linkURL="" linkTarget="">' .
                              '<caption>'.$ttle.$desc.'</caption>' .
                            '</image>';
                }

                $xml .= '</simpleviewergallery>';
            }

            $this->set('content', $xml);
            $this->render(false);
        } else {
            $this->javascripts = am($this->javascripts, 'http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js');
            $this->set(array(
                'id'     => $id,
                'width'  => $width,
                'height' => $height
            ));
        }
    } // view

    public function index () {
        //$this->Album->Behaviors->attach('Containable');
        //$this->Album->contain('Image');

        $data   = $main = $json = $imgs = array();
        $albums = $this->Album->find('all', array(
            'conditions' => array('Album.type'=>'events'),
            //'recursive'  => 0,
            'order'      => array('order', 'id DESC')
        ));

        $this->loadModel('Image');

        foreach ($albums as $i=>$a) {
            $data[$i] = $a['Album'];

            $data[$i]['name'] = htmlspecialchars($data[$i]['name'], ENT_COMPAT);

            foreach ($a['Image'] as $img) {
                $img['title'] = $a['Album']['name'];
                $img['descr'] = empty($img['description']) ? $a['Album']['description'] : $img['description'];
                $imgs[$i][]   = $img;
            }

            if ($a['Album']['image_id']) {
                $this->Image->id = $a['Album']['image_id'];
                $data[$i]['filename'] = $this->Image->field('filename');
            } else {
                $data[$i]['filename'] = 'default.png';
            }

            if ($i > 6) {
                $json[] = $data[$i];
            } else {
                $main[] = $data[$i];
            }
        }

        /*for ($x=0; $x<50; $x++) {
            $json[] = array(
                'name'     => 'ATP Zeta Essential Pack',
                'filename' => ''
            );
        }*/

        $this->stylesheet  = am($this->stylesheet, 'sexylightbox/sexylightbox');
        $this->javascripts = am($this->javascripts, 'http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js',
            'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js', 'jquery.easing.1.3', 'jquery.scrollTo', 'sexylightbox.v2.3.jquery.min');
        $this->set('data', $main);
        $this->set('count', $i);
        $this->set('json', json_encode($json));
        $this->set('images', $imgs);
    } // index
} // AlbumsController
?>